package com.chiaching.framwork.core.feign;

import com.alibaba.fastjson.JSONObject;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class DefaultErrorDecode implements ErrorDecoder {

    @Override
    public Exception decode(String s, Response response) {
        String content = null;
        try {
            InputStream inputStream = response.body().asInputStream();
            content = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            DefaultDecoder.ResponseEntity responseEntity = JSONObject.parseObject(content, DefaultDecoder.ResponseEntity.class);
            if (responseEntity == null) {
                return new ApiAccessException(response.request().url(), content);
            } else {
                return new ApiAccessException(response.request().url(), responseEntity);
            }
        } catch (Exception e) {
            return new ApiAccessException(response.request().url(), content);
        }
    }
}
